package com.bcx.wind.workflow.imp.cmd.managercmd;

import com.bcx.wind.workflow.access.QueryFilter;
import com.bcx.wind.workflow.cache.Cache;
import com.bcx.wind.workflow.core.constant.OrderStatus;
import com.bcx.wind.workflow.core.constant.TaskStatus;
import com.bcx.wind.workflow.entity.WindOrder;
import com.bcx.wind.workflow.entity.WindTask;
import com.bcx.wind.workflow.interceptor.Command;
import com.bcx.wind.workflow.interceptor.CommandContext;
import com.bcx.wind.workflow.support.Assert;
import com.bcx.wind.workflow.support.ObjectHelper;

import java.util.List;

import static com.bcx.wind.workflow.message.ErrorCode.ORDER_NOT_EXISTS;
import static com.bcx.wind.workflow.message.ErrorCode.RECOVERY_FAIL;

/**
 * 恢复流程命令
 *
 * @author zhanglei
 */
public class RecoveryOrderCommand implements Command<Integer> {

    /**
     * 流程实例ID
     */
    private String orderId;

    /**
     * 业务ID
     */
    private String businessId;

    /**
     * 执行数据
     */
    private CommandContext commandContext;

    public RecoveryOrderCommand(String orderId,String businessId){
        this.orderId = orderId;
        this.businessId = businessId;
    }

    @Override
    public Integer executor(CommandContext context) {
        try {
            this.commandContext = context;
            return execute();
        }catch (Exception e){
            context.log(e);
            return 0;
        }
    }

    private WindOrder buildOrder(){
        WindOrder windOrder = null;
        if(this.orderId != null){
            QueryFilter filter = new QueryFilter()
                    .setOrderId(this.orderId)
                    .setStatus(OrderStatus.stop.name());
            List<WindOrder> orders = this.commandContext.access().selectOrderInstanceList(filter);
            windOrder = ObjectHelper.isEmpty(orders) ? null : orders.get(0);
        }else if(this.businessId != null){
            QueryFilter filter = new QueryFilter()
                    .setBusinessId(businessId)
                    .setStatus(OrderStatus.stop.name());
            List<WindOrder> orders = this.commandContext.access().selectOrderInstanceList(filter);
            windOrder = ObjectHelper.isEmpty(orders) ? null : orders.get(0);
        }
        Assert.notEmptyError(RECOVERY_FAIL,windOrder);
        return windOrder;
    }

    private Integer execute() {
        //查询流程实例
        WindOrder windOrder = buildOrder();
        //查询流程实例下的任务
        QueryFilter filter = new QueryFilter()
                .setOrderId(windOrder.getId());
        List<WindTask>  windTasks = this.commandContext.access().selectTaskInstanceList(filter);

        //更新任务以及实例状态
        windOrder.setStatus(OrderStatus.run.name());
        this.commandContext.access().updateOrderInstance(windOrder);

        for(WindTask windTask : windTasks){
            windTask.setStatus(TaskStatus.run.name());
            this.commandContext.access().updateTaskInstance(windTask);
        }

        return 1;
    }
}
